<template>
  <div class="report-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>农户报案列表</h1>
    </div>

    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" size="default">
        <el-form-item label="保单编号" prop="policyId">
          <el-input
              v-model="searchForm.policyId"
              placeholder="请输入保单编号（支持数字和字符）"
              clearable
              style="width: 220px;"
              maxlength="20"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm" style="margin-left: 8px;">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          element-loading-text="正在加载数据..."
          style="width: 100%;"
          size="small"
      >
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="reportNo" label="报案号" width="180" align="center"></el-table-column>
        <el-table-column prop="policyId" label="保单编号" width="160" align="center">
          <template #default="scope">{{ scope.row.policyId || '-' }}</template>
        </el-table-column>
        <el-table-column prop="insuredId" label="投保人ID" width="120" align="center"></el-table-column>
        <el-table-column
            prop="reportTime"
            label="报案时间"
            width="180"
            :formatter="formatDateTime"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="disasterType"
            label="灾祸类型"
            width="120"
            :formatter="formatDisasterType"
            align="center"
        ></el-table-column>
        <!-- 报案状态：彩色文字渲染 -->
        <el-table-column label="报案状态" width="120" align="center">
          <template #default="scope">
            <span v-html="formatReportStatus(scope.row.reportStatus)"></span>
          </template>
        </el-table-column>
        <el-table-column
            prop="lossEstimate"
            label="预估损失(元)"
            width="140"
            :formatter="formatCurrency"
            align="center"
        ></el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row)">查看详情</el-button>
            <!-- 申请重开赔案：仅已结案状态显示 -->
            <el-button
                size="small"
                type="success"
                @click="handleReopenCase(scope.row)"
                style="margin-left: 8px;"
                v-if="canReopenCase(scope.row)"
            >
              申请重开赔案
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            size="small"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情弹窗 -->
    <el-dialog
        title="报案详情"
        v-model="detailDialogVisible"
        width="650px"
        :before-close="handleDetailDialogClose"
        destroy-on-close
    >
      <el-form
          :model="detailForm"
          label-width="140px"
          size="default"
          class="detail-form"
      >
        <!-- 基础字段 -->
        <el-form-item label="报案号">
          <el-input v-model="detailForm.reportNo" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="保单编号">
          <el-input v-model="detailForm.policyId" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="投保人ID">
          <el-input v-model="detailForm.insuredId" disabled placeholder="无"></el-input>
        </el-form-item>

        <!-- 时间相关字段 -->
        <el-form-item label="报案时间">
          <el-input v-model="detailForm.reportTime" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="灾祸发生时间">
          <el-input v-model="detailForm.disasterOccurTime" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="受理时间">
          <el-input v-model="detailForm.handleTime" disabled placeholder="无"></el-input>
        </el-form-item>

        <!-- 灾祸相关字段 -->
        <el-form-item label="灾祸类型">
          <el-input v-model="detailForm.disasterTypeText" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="灾祸发生地点">
          <el-input v-model="detailForm.disasterLocation" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="损失描述">
          <el-input
              type="textarea"
              v-model="detailForm.lossDescription"
              disabled
              rows="3"
              placeholder="无"
          ></el-input>
        </el-form-item>
        <el-form-item label="预估损失金额(元)">
          <el-input v-model="detailForm.lossEstimate" disabled placeholder="0.00"></el-input>
        </el-form-item>

        <!-- 报案人信息 -->
        <el-form-item label="报案人姓名">
          <el-input v-model="detailForm.reporterName" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="报案人联系电话">
          <el-input v-model="detailForm.reporterPhone" disabled placeholder="无"></el-input>
        </el-form-item>

        <!-- 处理状态字段 -->
        <el-form-item label="报案状态">
          <el-input v-model="detailForm.reportStatusText" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="驳回原因" v-if="detailForm.reportStatus === 9">
          <el-input
              type="textarea"
              v-model="detailForm.rejectReason"
              disabled
              rows="2"
              placeholder="无"
          ></el-input>
        </el-form-item>
        <el-form-item label="报案受理员工号">
          <el-input v-model="detailForm.reportWorkNo" disabled placeholder="无"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDetailDialogClose">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 申请重开赔案弹窗（适配String类型保单编号） -->
    <el-dialog
        title="申请重开赔案"
        v-model="reopenDialogVisible"
        width="500px"
        :before-close="handleDialogClose"
        destroy-on-close
    >
      <el-form
          ref="reopenFormRef"
          :model="reopenForm"
          :rules="reopenFormRules"
          label-width="120px"
          size="default"
      >
        <!-- 报案号 -->
        <el-form-item label="报案号" prop="reportNo">
          <el-input v-model="reopenForm.reportNo" disabled placeholder="无"></el-input>
        </el-form-item>
        <!-- 保单编号（关键修改：适配String类型） -->
        <el-form-item label="保单编号" prop="policyId">
          <el-input
              v-model="reopenForm.policyId"
              disabled
              placeholder="无"
              type="text">
          </el-input>
        </el-form-item>
        <!-- 申请人 -->
        <el-form-item label="申请人" prop="applicant" required>
          <el-input
              v-model="reopenForm.applicant"
              placeholder="请输入申请人姓名"
              maxlength="50"
          ></el-input>
        </el-form-item>
        <!-- 申请时间 -->
        <el-form-item label="申请时间" prop="applyTime" required>
          <el-date-picker
              v-model="reopenForm.applyTime"
              type="datetime"
              placeholder="选择申请时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
              disabled
          ></el-date-picker>
        </el-form-item>
        <!-- 重开原因 -->
        <el-form-item label="重开原因" prop="reopenReason" required>
          <el-input
              v-model="reopenForm.reopenReason"
              type="textarea"
              rows="4"
              placeholder="请详细说明申请重开赔案的原因"
              maxlength="500"
          ></el-input>
        </el-form-item>
        <!-- 重开赔案金额 -->
        <el-form-item label="重开赔案金额(元)" prop="reopenMoney" required>
          <el-input
              v-model="reopenForm.reopenMoney"
              placeholder="请输入重开后的赔案金额（如：1000.50）"
              maxlength="20"
              @input="handleAmountInput"
              @blur="formatAmountOnBlur"
              type="number"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitReopenForm">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import hxxp from '@/utils/hxxp';

// 1. 核心状态管理
const loading = ref(false);               // 全局加载状态
const tableData = ref([]);               // 表格数据源
const detailDialogVisible = ref(false);  // 查看详情弹窗显示状态
const reopenDialogVisible = ref(false);  // 重开赔案弹窗显示状态
const reopenFormRef = ref(null);         // 重开表单引用

// 2. 查询表单数据（保单编号为String类型）
const searchForm = reactive({
  policyId: ''   // 保单编号（字符串，支持数字和字符）
});

// 3. 分页配置
const pagination = reactive({
  pageNum: 1,    // 当前页码
  pageSize: 5,   // 每页条数
  total: 0       // 总记录数
});

// 4. 查看详情表单数据
const detailForm = reactive({
  id: '',                          // 报案唯一ID
  reportNo: '',                    // 报案号
  policyId: '',                    // 保单编号（String类型）
  insuredId: '',                   // 投保人ID
  reportTime: '',                  // 报案时间（格式化后）
  disasterType: '',                // 灾祸类型（原始数字）
  disasterTypeText: '',            // 灾祸类型（中文文本）
  disasterOccurTime: '',           // 灾祸发生时间（格式化后）
  disasterLocation: '',            // 灾祸发生地点
  lossDescription: '',             // 损失描述
  lossEstimate: '',                // 预估损失金额（格式化后）
  reporterName: '',                // 报案人姓名
  reporterPhone: '',               // 报案人电话
  reportStatus: '',                // 报案状态（原始数字）
  reportStatusText: '',            // 报案状态（中文文本）
  rejectReason: '',                // 驳回原因
  reportWorkNo: '',                // 受理员工号
  handleTime: ''                   // 受理时间（格式化后）
});

// 5. 重开赔案表单数据（保单编号为String类型）
const reopenForm = reactive({
  reportNo: '',          // 报案号（String）
  policyId: '',          // 保单编号（关键修改：String类型）
  applicant: '',         // 申请人（String）
  applyTime: '',         // 申请时间（String，yyyy-MM-dd HH:mm:ss）
  reopenReason: '',      // 重开原因（String）
  reopenMoney: ''        // 重开赔案金额（String）
});

// 6. 表单校验规则（适配String类型保单编号）
const validateAmount = (rule, value, callback) => {
  if (value === null || value === '') {
    callback();
    return;
  }
  const amountRegex = /^\d+(\.\d{1,2})?$/;
  if (!amountRegex.test(value)) {
    callback(new Error('请输入有效的金额（整数或最多两位小数）'));
  } else {
    callback();
  }
};

const validateApplyTime = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择申请时间'));
    return;
  }
  const timeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
  if (!timeRegex.test(value)) {
    callback(new Error('申请时间格式错误，请使用yyyy-MM-dd HH:mm:ss格式'));
  } else {
    callback();
  }
};

// 新增保单编号字符串校验规则
const validatePolicyId = (rule, value, callback) => {
  if (!value) {
    callback(); // 非必填，由后端控制是否必填
    return;
  }
  // 支持数字、字母和常见符号（根据实际业务调整）
  const policyIdRegex = /^[0-9A-Za-z\-_]{1,20}$/;
  if (!policyIdRegex.test(value)) {
    callback(new Error('保单编号仅支持数字、字母、-和_，长度不超过20'));
  } else {
    callback();
  }
};

const reopenFormRules = reactive({
  applicant: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    { max: 50, message: '申请人姓名不能超过50个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '申请人姓名仅支持中文、英文、数字', trigger: 'blur' }
  ],
  applyTime: [
    { required: true, message: '请选择申请时间', trigger: 'change' },
    { validator: validateApplyTime, trigger: 'blur' }
  ],
  policyId: [
    { validator: validatePolicyId, trigger: 'blur' } // 保单编号字符串校验
  ],
  reopenReason: [
    { required: true, message: '请输入重开原因', trigger: 'blur' },
    { max: 500, message: '重开原因不能超过500个字符', trigger: 'blur' }
  ],
  reopenMoney: [
    { required: true, message: '请输入重开赔案金额', trigger: 'blur' },
    { validator: validateAmount, trigger: 'blur' },
    { min: 0, message: '金额不能为负数', trigger: 'blur' }
  ]
});

// 7. 页面挂载时加载列表数据
onMounted(() => {
  fetchReportList();
});

// 8. 核心方法：获取报案列表（保单编号为String类型传递）
const fetchReportList = async () => {
  loading.value = true;
  try {
      const response = await hxxp.get('/aiClaimReport/all', {
        params: {
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          policyId: searchForm.policyId || undefined ,
          reportStatus: 8// 直接传递字符串，无需转换
        }
      });

    if (response.code === 100200) {
      // 根据实际返回的数据结构进行解析
      const result = response.data;
      tableData.value = result.list || [];
      pagination.total = result.total || 0;
      pagination.pageNum = result.pageNum || 1;
      pagination.pageSize = result.pageSize || 5;
    } else {
      ElMessage.error(`获取数据失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取报案列表异常：', error);
    ElMessage.error('网络异常，请检查接口连接或后端服务状态');
  } finally {
    loading.value = false;
  }
};

// 9. 工具方法：格式化日期时间
const formatDateTime = (row, column, dateStr) => {
  if (!dateStr) return '-';
  const normalizedDateStr = String(dateStr).replace('T', ' ').split('.')[0];
  const date = new Date(normalizedDateStr);
  if (isNaN(date.getTime())) return '日期无效';

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(',', '');
};

// 10. 工具方法：灾祸类型数字转中文
const formatDisasterType = (row, column, type) => {
  const typeMap = {
    '1': '暴雨',
    '2': '洪水',
    '3': '病虫害',
    '4': '疫病',
    '5': '其他'
  };
  return typeMap[type] || '未知';
};

// 11. 工具方法：报案状态数字转中文
const getReportStatusText = (status) => {
  const statusMap = {
    '1': '待调度',
    '2': '待查勘',
    '3': '待立案',
    '4': '已立案',
    '5': '待理算',
    '6': '待核赔',
    '7': '待结案',
    '8': '已结案',
    '9': '已驳回'
  };
  return statusMap[status] || '未知';
};

// 12. 工具方法：格式化金额
const formatCurrency = (row, column, amount) => {
  if (amount === null || amount === undefined) return '0.00';
  const num = Number(amount);
  if (isNaN(num)) return '0.00';
  return num.toFixed(2);
};

// 13. 工具方法：表格状态列彩色文字
const formatReportStatus = (status) => {
  const statusText = getReportStatusText(status);
  const statusColorMap = {
    '1': '#faad14', '2': '#faad14', '3': '#faad14',
    '4': '#1890ff', '5': '#1890ff', '6': '#1890ff', '7': '#1890ff',
    '8': '#52c41a',
    '9': '#ff4d4f'
  };
  const color = statusColorMap[status] || '#8c8c8c';
  return `<span style="color: ${color}; font-weight: 500;">${statusText}</span>`;
};

// 14. 查询操作：执行查询
const handleSearch = () => {
  pagination.pageNum = 1;
  fetchReportList();
};

// 15. 查询操作：重置查询条件
const resetForm = () => {
  searchForm.policyId = '';
  pagination.pageNum = 1;
  fetchReportList();
};

// 16. 分页操作：每页条数改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchReportList();
};

// 17. 分页操作：当前页码改变
const handleCurrentChange = (val) => {
  pagination.pageNum = val;
  fetchReportList();
};

// 18. 查看详情操作：打开弹窗并填充数据
const handleView = (row) => {
  Object.keys(detailForm).forEach(key => {
    detailForm[key] = '';
  });

  detailForm.id = row.id || '';
  detailForm.reportNo = row.reportNo || '';
  detailForm.policyId = row.policyId || ''; // 字符串类型赋值
  detailForm.insuredId = row.insuredId || '';
  detailForm.reportTime = formatDateTime(null, null, row.reportTime);
  detailForm.disasterType = row.disasterType || '';
  detailForm.disasterTypeText = formatDisasterType(null, null, row.disasterType);
  detailForm.disasterOccurTime = formatDateTime(null, null, row.disasterOccurTime);
  detailForm.disasterLocation = row.disasterLocation || '';
  detailForm.lossDescription = row.lossDescription || '';
  detailForm.lossEstimate = formatCurrency(null, null, row.lossEstimate);
  detailForm.reporterName = row.reporterName || '';
  detailForm.reporterPhone = row.reporterPhone || '';
  detailForm.reportStatus = row.reportStatus || '';
  detailForm.reportStatusText = getReportStatusText(row.reportStatus);
  detailForm.rejectReason = row.rejectReason || '';
  detailForm.reportWorkNo = row.reportWorkNo || '';
  detailForm.handleTime = formatDateTime(null, null, row.handleTime) || '-';

  detailDialogVisible.value = true;
};

// 19. 查看详情操作：关闭弹窗
const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
};

// 20. 重开赔案操作：判断是否允许重开
const canReopenCase = (row) => {
  return row.reportStatus === 8;
};

// 21. 重开赔案操作：打开弹窗并填充数据（保单编号为String类型）
const handleReopenCase = (row) => {
  if (reopenFormRef.value) {
    reopenFormRef.value.resetFields();
  }

  // 关键修改：保单编号作为字符串直接赋值
  reopenForm.reportNo = row.reportNo || '';
  reopenForm.policyId = row.policyId || ''; // 字符串类型赋值

  // 生成申请时间
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  const second = String(now.getSeconds()).padStart(2, '0');
  reopenForm.applyTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;

  reopenDialogVisible.value = true;
};

// 22. 重开赔案操作：关闭弹窗
const handleDialogClose = () => {
  if (reopenFormRef.value) {
    reopenFormRef.value.resetFields();
  }
  reopenDialogVisible.value = false;
};

// 23. 金额输入处理
const handleAmountInput = (value) => {
  if (!value) {
    reopenForm.reopenMoney = '';
    return;
  }
  const cleaned = value.toString().replace(/[^0-9.]/g, '');
  const parts = cleaned.split('.');
  let formatted = parts[0];
  if (parts.length > 1) {
    formatted += '.' + parts[1].substring(0, 2);
  }
  if (formatted.startsWith('0') && formatted.length > 1 && !formatted.startsWith('0.')) {
    formatted = formatted.replace(/^0+/, '');
    if (formatted === '') formatted = '0';
  }
  reopenForm.reopenMoney = formatted;
};

// 24. 金额失去焦点格式化
const formatAmountOnBlur = () => {
  if (!reopenForm.reopenMoney) return;
  const num = parseFloat(reopenForm.reopenMoney);
  if (!isNaN(num)) {
    reopenForm.reopenMoney = num.toFixed(2);
  }
};

// 25. 重开赔案操作：提交申请（保单编号为String类型）
const submitReopenForm = async () => {
  const validatePass = await new Promise((resolve) => {
    reopenFormRef.value.validate((isValid) => {
      resolve(isValid);
    });
  });
  if (!validatePass) return;

  try {
    loading.value = true;
    // 提交数据（保单编号为String类型）
    const submitData = {
      reportNo: reopenForm.reportNo.trim(),
      policyId: reopenForm.policyId.trim(), // 字符串类型提交
      applicant: reopenForm.applicant.trim(),
      applyTime: reopenForm.applyTime,
      reopenReason: reopenForm.reopenReason.trim(),
      reopenMoney: reopenForm.reopenMoney.trim(),
      approveStatus: 1
    };

    // 调试信息
    console.log('提交数据:', submitData);
    console.log('各字段类型:');
    Object.keys(submitData).forEach(key => {
      console.log(`${key}: ${typeof submitData[key]}`);
    });

    const response = await hxxp.put(
        '/aiClaimReopen/reopenAdd',
        submitData,
        {
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          }
        }
    );

    if (response.data.code === 100200 || response.data.success) {
      ElMessage.success('重开赔案申请提交成功');
      handleDialogClose();
      fetchReportList();
    } else {
      ElMessage.error(`提交失败：${response.data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交重开申请异常：', error);
    if (error.response) {
      console.error('后端状态码：', error.response.status);
      console.error('后端错误数据：', error.response.data);
      // 显示后端返回的具体错误信息
      const errorMsg = error.response.data.msg ||
          (error.response.data.errors ? JSON.stringify(error.response.data.errors) : '请求参数错误');
      ElMessage.error(`提交失败：${errorMsg}`);
    } else if (error.request) {
      ElMessage.error('提交失败：未收到后端响应');
    } else {
      ElMessage.error(`提交失败：${error.message}`);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.report-list-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 18px;
  color: #1f2329;
  margin: 0;
  font-weight: 600;
}

.search-card {
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
}

.search-form {
  padding: 16px 0;
}

.table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 12px;
  text-align: right;
}

.detail-form {
  margin-top: 10px;
}

.detail-form .el-form-item {
  margin-bottom: 12px;
}

::v-deep .el-table__cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

::v-deep .el-date-editor--datetime {
  width: 100%;
}
</style>
